package com.atguigu.tingshu.user.pattern.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.pattern.DeliveryStrategy;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName : TrackDelivery
 * Package : com.atguigu.tingshu.user.pattern.impl
 * Description :
 * <p>
 * Author: LHZ
 * Create: 2025/8/1 23:33
 * Version: 1.0
 */
@Slf4j
@SuppressWarnings({"all"})
@Component(SystemConstant.ORDER_ITEM_TYPE_TRACK)
public class TrackDelivery implements DeliveryStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;
    @Autowired
    private UserPaidTrackService userPaidTrackService;
    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Override
    public void delivery(UserPaidRecordVo vo) {
        //获取订单号
        String orderNo = vo.getOrderNo();
        //声音
        //根据订单号从数据库中查询是否已有购买记录
        Long count = userPaidTrackMapper.selectCount(
                new LambdaQueryWrapper<UserPaidTrack>()
                        .eq(UserPaidTrack::getOrderNo,orderNo)
        );
        if(count > 0){
            log.info("已存在该订单:{}的已购声音记录", orderNo);
            return;
        }
        //封装购买声音记录对象,将记录存入到数据库中
        List<Long> itemIdList = vo.getItemIdList();
        if(!CollectionUtils.isEmpty(itemIdList)){
            //调用远程服务从声音对象中获取专辑id
            TrackInfo trackInfo = albumFeignClient.getTrackInfo(itemIdList.get(0)).getData();
            Long albumId = trackInfo.getAlbumId();
            Assert.notNull(trackInfo,"声音{}信息为空",itemIdList.get(0));
            List<UserPaidTrack> list = new ArrayList<>();
            for (Long item : itemIdList) {
                UserPaidTrack userPaidTrack = new UserPaidTrack();
                userPaidTrack.setOrderNo(orderNo);
                userPaidTrack.setUserId(vo.getUserId());
                userPaidTrack.setAlbumId(albumId);
                userPaidTrack.setTrackId(item);
                list.add(userPaidTrack);
            }
            //批量插入
            userPaidTrackService.saveBatch(list);
        }


    }
}